(function (win, doc) {

  /**
   *cookie
   */
  const cookie = {
    /*
    作用：通过传key值，返回需要的当前key的value值，即封装cookie的查
    参数：name->cookie中的key值
    返回：有则返回value，无则返回""空
    调用方法 console.log(getCookie("phone"));
    */
    get (name) {
      name += '_' + location.port;
      var cookieTxt = document.cookie;
      var arr = cookieTxt.split("; ");
      for(var i=0; i<arr.length; i++) {
        var arr1 = arr[i].split("=");
        if(decodeURIComponent(arr1[0]) == name) {
          return decodeURIComponent(arr1[1]);
        }
      }
      return "";
    },
    /*
    作用：封装cookie的增和改
    参数：name->当前这条cookie的名称，value->当前cookie的值，day->当前cookie存在的天数为0或为空则为有效时间是当前会话，path->为当前cookie的有效路径不设则为根路径/
    */
    set (name,value,day,path) {
      name += '_' + location.port;
      var result = "";
      result += encodeURIComponent(name)+"="+encodeURIComponent(value);
      if(day) {
        var date = new Date();
        date.setDate(date.getDate()+day);
        result += "; expires="+date;
      }
      if(path) {
        result += "; path="+path;
      } else {
        result += "; path=/";
      }
      document.cookie = result;
    },
    /*
    作用：封装cookie的删
    参数：name->需要删除的cookie的名称
    */
    remove (name) {
      name += '_' + location.port;
      this.set(name,"",-1);
    }
  }


  /**
    *格式化时间
    *@param {String} time [可以new Date()的时间]
    *@param {String} format [时间格式化类型
        yyyy            年
        M               月       不用补0
        MM              月       需要补0
        W               周       不用补0
        WW              周       需要补0
        d               日       不用补0
        dd              日       需要补0
        H               24小时    不用补0
        HH              24小时    需要补0
        h               12小时    不用补0
        hh              12小时    需要补0
        m               分       不用补0
        mm              分       需要补0
        s               秒       不用补0
        ss              秒       需要补0
        timestamp       时间戳   
        例子：yyyy年MM月dd日 HH:mm:ss
      ]
   */
  function switchTime (time, format) {
    if(!time) {
      return time || '';
    }
    format = format ? format : 'yyyy年MM月dd日 HH:mm:ss';
    var res = format;
    var date = new Date(time);
    var timestamp = date.getTime(),
      year = date.getFullYear(),
      month = date.getMonth() + 1,
      day = date.getDate(),
      hours = date.getHours(),
      minutes = date.getMinutes(),
      seconds = date.getSeconds(),
      week = date.getDay(); // 0是星期日
    // 判断传入是否可以转换为时间
    if (!year) {
      return time;
    }
    // 替换时间戳
    res = res.replace(/timestamp/g, timestamp);
    // 替换年
    res = res.replace(/yyyy/g, year);
    // 替换月
    res = res.replace(/MM/g, makeUpNum(month));
    res = res.replace(/M/g, month);
    // 替换日
    res = res.replace(/dd/g, makeUpNum(day));
    res = res.replace(/d/g, day);
    // 替换时
    res = res.replace(/HH/g, makeUpNum(hours));
    res = res.replace(/H/g, hours);
    // 替换分
    res = res.replace(/mm/g, makeUpNum(minutes));
    res = res.replace(/m/g, minutes);
    // 替换秒
    res = res.replace(/ss/g, makeUpNum(seconds));
    res = res.replace(/s/g, seconds);
    // 替换周
    res = res.replace(/WW/g, makeUpNum(week));
    res = res.replace(/W/g, week);
    return res;
  }

  /**
   *数字补0
   @param {Number} val [需要补0的数]
   */
  function makeUpNum (val) {
      return val < 10 ? '0' + parseInt(val) : val;
  }

  /**
   *拷贝
   */
  function copy (data) {
      return JSON.parse(JSON.stringify(data));
  }

  /**
   *判断是否为空
   *@return {Boolean} [true为空，false不为空]
   */
  function isEmpty (val) {
    if (typeof val == 'string') {
      val = val.trim();
    }
    return !val && val!==0 && typeof val!=="boolean"?true:false;
  }

  // 保留小数位数
  /**
   *保留几位小数
   *@param {Number} val [传入的值]
   *@param {Number} num [保留小数的位数]
   *@return {Number} [保留小数位数后的数字]
   */
  function toFixed(val, num) {
    var res = Number(val);
    if (!res) {
      return res;
    }
    res = res.toFixed(num);
    var arr = ('' + res).split('.');
    if (arr[1].length > num) {
      arr[1] = arr[1].slice(0, num);
      res = arr.join('.');
    }
    return res;
  }

  /*使用方法
  <el-input v-model="form.num" @blur="form.num = $number(form.num,2)"></el-input>
  */
  /**
   *转换为数字小数位数
   *@param {Number} data 需要保留小数点的数，如果不是数，返回'' 
   *@param {Number} precision 小数点位数
   *@return {Number} 返回截取小数点后的数，如果不是数，返回''
   */
  function toNumber (data, precision) {
    let value = data;
    // 判断是否是数字
    if (!/^(\-|\+)?\d+(\.\d+)?$/.test(value)) {
      return '';
    }
    var content = parseFloat(value);
    if (!content) {
      content = 0.00;
    }
    let arg_precision = precision || 0;//默认保留至整数
    return Number(content.toFixed(arg_precision));
  }

  /**
   *根据身份证获取出生日期
   */
  function getBirthdayByIdcard (idcard) {
    var res = '';
    if (idcard) {
      idcard = '' + idcard;
    } else {
      return '';
    }
    if (idcard.length == 15) {
      res = '19' + idcard.slice(6,8) + '-' + idcard.slice(8,10) + '-' + idcard.slice(10,12);
    } else if (idcard.length == 18) {
      res = idcard.slice(6,10) + '-' + idcard.slice(10,12) + '-' + idcard.slice(12,14);
    }
    return res;
  }

  /**
   *根据身份证获取性别
   * 1男2女
   */
  function getSexByIdcard (idcard) {
    var res = '';
    if (idcard) {
      idcard = '' + idcard;
    } else {
      return '';
    }
    if (idcard.length == 15) {
      res = parseInt(idcard[14]) % 2 == 1 ? 1 : 2;
    } else if (idcard.length == 18) {
      res = parseInt(idcard[16]) % 2 == 1 ? 1 : 2;
    }
    return res;
  }

  /*使用方法
  obj = { aa: [ {name: '张三'} ] }
  getValueByKeys(obj, 'aa', 0, 'name');
  getValue () {
    return getValueByKeys(this.detail, ...arguments);
  }
  */
  /**
   *根据key获取对象的相应值，后面的都是参数，第二个是第一级，第三个是第二级参数
   */
  function getValueByKeys () {
      var args = arguments;
      var res = args[0]; // 第一个是对象
      if (!res) {
          return '';
      }
      for (var i = 1; i < args.length; i++) {
          var item = args[i];
          if (isEmpty(res[item])) {
              res = '';
              break;
          } else {
              res = res[item];
          }
      }
      return res;
  }

  /**
   * 获取时间列表 
   **/
  function getTimesByLength(length) {
    let res = [];
    for(let i = length-1; i >= 0; i--) {
      var date = new Date();
      date.setDate(date.getDate()-i);
      res.push(switchTime(date, 'MM.dd'));
    }
    return res;
  }

  /**
   * 获取浏览器类型
   */
  function getBrowserType () {
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
      var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器
      var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判断是否IE浏览器
      var isIE11 = !!window.ActiveXObject || "ActiveXObject" in window; // 判断是否IE11
      var isFF = userAgent.indexOf("Firefox") > -1; //判断是否Firefox浏览器
      var isSafari = userAgent.indexOf("Safari") > -1; //判断是否Safari浏览器
      var isChrome = userAgent.indexOf('Chrome') > -1; // 判断你是否Chrome乱临其
      if (isIE || isIE11) {
          var IE5 = IE55 = IE6 = IE7 = IE8 = false;
          var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
          reIE.test(userAgent);
          var fIEVersion = parseFloat(RegExp["$1"]);
          IE55 = fIEVersion == 5.5;
          IE6 = fIEVersion == 6.0;
          IE7 = fIEVersion == 7.0;
          IE8 = fIEVersion == 8.0;
          if (IE55) {
              return "IE55";
          }
          if (IE6) {
              return "IE6";
          }
          if (IE7) {
              return "IE7";
          }
          if (IE8) {
              return "IE8";
          } else {
            return "IE";
          }
      }//isIE end
    if (isFF) {
      return "Firefox";
    }
    if (isOpera) {
      return "Opera";
    }
    if (isSafari) {
      return "Safari";
    }
    if (isChrome) {
      return 'Chrome';
    }
  }

  function parseURL(url) {
    var a =  document.createElement('a');
    a.href = url;
    return {
      source: url,
      protocol: a.protocol.replace(':',''),
      host: a.hostname,
      port: a.port,
      query: a.search,
      params: (function(){
        let search = decodeURIComponent(a.search);
        var ret = {},
          seg = search.replace(/^\?/,'').split('&'),
          len = seg.length, i = 0, s;
        for (;i<len;i++) {
          if (!seg[i]) { continue; }
          s = seg[i].split('=');
          ret[s[0]] = s[1];
        }
        return ret;
      })(),
      file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
      hash: a.hash.replace('#',''),
      path: a.pathname.replace(/^([^\/])/,'/$1'),
      relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
      segments: a.pathname.replace(/^\//,'').split('/')
    };
  }

  // 组装路由参数
  function joinUrl(path, query) {
    let arr = [];
    for(let key in query) {
      arr.push(key+'='+query[key]);
    }
    if(arr.length) {
      path+='?'+arr.join('&')
    }
    return path;
  }

  // base64转文件
  function base64ToFile(base64, fileName) {
    var arr = base64.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    var theBlob = new Blob([u8arr], { type: mime });
    theBlob.lastModifiedDate = new Date();  // 文件最后的修改日期
    theBlob.name = fileName;                // 文件名
    return new File([theBlob], fileName, {type: theBlob.type, lastModified: Date.now()});
  }

  // 防抖
  function debounce(fn, t) {
    const delay = t || 500;
    let timer;
    return function () {
      const args = arguments;
      const context = this;
      clearTimeout(timer);
      timer = setTimeout(() => {
        timer = null;
        fn.apply(context, args);
      }, delay);
    }
  }

  // 获取年龄
  function getAge(birthtime, endtime, empty = '') {
    if(!birthtime || !endtime) {
      return empty;
    }
    let d1 = new Date(birthtime);
    let year1 = d1.getFullYear(), month1 = makeUpNum(d1.getMonth()+1), day1 = makeUpNum(d1.getDate());
    let d2 = new Date(endtime);
    let year2 = d2.getFullYear(), month2 = makeUpNum(d2.getMonth()+1), day2 = makeUpNum(d2.getDate());
    let year = year2 - year1;
    return ''+month1+day1 < ''+month2+day2 ? year+1 : year;
  }

  // 使用a表单点击下载
  function adownload (title, url) {
    let link = document.createElement('a');
    link.style.display = 'none';
    link.download = title;
    link.href = url;
    // 触发点击
    document.body.appendChild(link);
    link.click();
    // 然后移除
    document.body.removeChild(link);
  }

  /**
   * 等待时间
   * @param {String} time [等待的时间]
   **/
  const waitTimeout = function (time) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve();
      }, time);
    })
  }

  win.Tools = {
    cookie: cookie,
    switchTime: switchTime,
    makeUpNum: makeUpNum,
    copy: copy,
    isEmpty: isEmpty,
    toFixed: toFixed,
    toNumber: toNumber,
    getBirthdayByIdcard: getBirthdayByIdcard,
    getSexByIdcard: getSexByIdcard,
    getTimesByLength: getTimesByLength,
    getBrowserType: getBrowserType,
    parseURL: parseURL,
    joinUrl: joinUrl,
    base64ToFile: base64ToFile,
    debounce: debounce,
    getAge: getAge,
    adownload: adownload,
    waitTimeout: waitTimeout,
  };
})(window, document)

  

